package com.ruoyi.system.controller;

import cn.hutool.json.JSONObject;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.web.domain.AjaxResult;
import com.ruoyi.system.domain.Hot;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import cn.hutool.json.JSONUtil;
import java.util.*;

/**
 * Redis的应用场景：：计数器
 * @Author lgy
 * @Version 1.0
 * @description: TODO
 * @date 2023/3/21 16:22
 */
@RestController
@RequestMapping("/hot")
public class HotController {

    private Set set = new HashSet();

    @Autowired
    RedisTemplate redisTemplate;

    /**
     *  关键词  点击率
     * @param hot
     * @return
     */
    @RequestMapping("/save")
    public R save(String hot)
    {
        if(Objects.nonNull(hot))
        {
            //判断是否有Key
            if(!redisTemplate.hasKey("hit"))
            {
                redisTemplate.opsForZSet().add("hit",hot,1); //没有 创建并加入value
            }else
            {
                redisTemplate.opsForZSet().incrementScore("hit",hot,1); //有 则递增
            }
        }
        return R.ok();
    }

    /**
     *  查询热搜前五
     * @return
     */
    @RequestMapping("/search")
    public AjaxResult search()
    {
        List<Hot> list = new ArrayList();
        if(redisTemplate.hasKey("hit"))
        {
            Set hit = redisTemplate.opsForZSet().reverseRangeWithScores("hit", 0, 4);
            for (Object o : hit) {
                if(null != o)
                {
                    JSONObject jsonObject = JSONUtil.parseObj(o);
                    String value = jsonObject.get("value").toString();
                    String score = jsonObject.get("score").toString();
                    Hot hot = new Hot(value,Double.parseDouble(score));
                    list.add(hot);
                }
            }
        }
        return AjaxResult.success(list);
    }
}
